package cn.yuan.user.controller;

import cn.yuan.basic.Exception.BusinessException;
import cn.yuan.basic.util.PageList;
import cn.yuan.user.domain.User;
import cn.yuan.user.dto.UserDto;
import cn.yuan.user.query.UserQuery;
import cn.yuan.user.service.IUserService;
import cn.yuan.util.AjaxResult.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口",description = "用户接口详细描述")
public class UserController {
    @Autowired
    private IUserService userService;

    @GetMapping("/{id}")
    @ApiOperation(value = "用户查找",notes = "根据ID查找用户")
    public User findOne(@PathVariable("id")Long id){
        return userService.loadById(id);
    }

    @GetMapping
    @ApiOperation(value = "查询所有用户",notes = "根据ID查找用户")
    public List<User> findAll(){
        return userService.loadAll();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户",notes = "根据ID删除用户")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败");
        }
    }

    @PatchMapping
    @ApiOperation(value = "批量删除用户",notes = "根据ID删除用户")
    public AjaxResult batchDel(@RequestBody Long[] ids){
        System.out.println(ids);
        try {
            userService.batchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败");
        }
    }

    @PutMapping
    @ApiOperation(value = "添加或者修改用户",notes = "添加或者修改用户")
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if(user.getId()==null){
                userService.save(user);
            }else {
                userService.update(user);
            }
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("操作失败");
        }
    }

    @PostMapping
    @ApiOperation(value = "查询分页",notes = "分页查询用户")
    public PageList<User> queryForPage(@RequestBody UserQuery userQuery){
        return userService.queryForPage(userQuery);
    }

    @PostMapping("/register/phone")
    public AjaxResult phoneRegister(@RequestBody UserDto userDto){
        try {
            userService.phoneRegister(userDto);
            return AjaxResult.me();
        } catch (BusinessException e) {//捕获业务异常
            e.printStackTrace();
            return AjaxResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("系统繁忙，稍后重试！！");
        }

    }
}
